﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAO
{
    public class DonHangDAO
    {
        private FDeal4Entities db;

        public DonHangDAO()
        {
            db = new FDeal4Entities();
        }

        public List<DONHANG> LietKe()
        {
            return db.DONHANG.ToList();
        }

        public DONHANG LayID(string id)
        {
            var tl = db.DONHANG.SingleOrDefault(t => t.IDDONHANG == id);
            return tl;
        }

        public DONHANG TimTen(String keyWord)
        {
            var tl = db.DONHANG.SingleOrDefault(t => t.IDDONHANG.Contains(keyWord));
            return tl;
        }

        public bool Them(DONHANG tl)
        {
            try
            {
                db.DONHANG.AddObject(tl);
                db.SaveChanges();
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

        public bool Xoa(DONHANG tl)
        {
            try
            {
                db.DONHANG.DeleteObject(tl);
                db.SaveChanges();
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

        public bool Sua(DONHANG tl)
        {
            try
            {
                DONHANG t1 = db.DONHANG.Single(t => t.IDDONHANG == tl.IDDONHANG);
                t1.IDDONHANG = tl.IDDONHANG;
                t1.IDTHANHTOAN = tl.IDTHANHTOAN;
                t1.DIACHINHAN = tl.DIACHINHAN;
                t1.TINHTHANH = tl.TINHTHANH;
                t1.QUANHUYEN = tl.QUANHUYEN;
                t1.IDDEAL = tl.IDDEAL;
                t1.SOLUONG = tl.SOLUONG;
                t1.TONGGIA = tl.TONGGIA;
                t1.HINHTHUCNHANHANG = tl.HINHTHUCNHANHANG;
                t1.TAIKHOAN = tl.TAIKHOAN;                
                db.SaveChanges();
                return true;
            }
            catch (System.Exception ex)
            {
            	return false;
            }
        }

        public List<DONHANG> DonHangMoiNhat()
        {
            return db.DONHANG.OrderByDescending(p => p.IDDONHANG).Take(1).ToList();
        }

        // added by Khuong
        public List<DONHANG> getDsDonHangCuaDN(string idDoanhNghiep)
        {
            List<DONHANG> dsDh = db.DONHANG.ToList();
            List<DONHANG> kq = new List<DONHANG>();

            for (int i = 0; i < dsDh.Count; i++)
            {
                if (dsDh[i].TAIKHOAN == idDoanhNghiep)
                    kq.Add(dsDh[i]);
            }

            return kq;
        }
    }
}
